/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include<stdio.h>
#include<string.h>

#include "sht30.h"
#include "esp8266.h"
#include "mqtt_esp.h"
#include "atcmd.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

#define DEF_ROUTER_SSID          "wifi_id"
#define DEF_ROUTER_PWD           "password"


#define MQTT_BROKER_HOSTNAME     "a1LcxRla2VF.iot-as-mqtt.cn-shanghai.aliyuncs.com"
#define MQTT_BROKER_PORT          1883     
#define MQTT_BROKER_USERNAME     "DHT11&a1LcxRla2VF"
#define MQTT_BROKER_PASSWORD     "926CA3D91E0FD79A1ADE2E6C2183756D818D98BD"

#define MQTT_CLIENT_ID           "12345|securemode=3,signmethod=hmacsha1|"  
#define MQTT_TOPIC               "/sys/a1LcxRla2VF/DHT11/thing/event/property/post"

#define	WIFI_CONNECT			(1<<0)
#define MQTT_CONNECT			(1<<1)

#define	AT_PING_ID				 "4.2.2.2"


/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
typedef struct
{
    char def_router_ssid[16];
    char def_router_pwd[16];

    char mqtt_broker_hostname[64];
    int  mqtt_broker_port;
    char mqtt_broker_username[24];
    char mqtt_broker_password[64];
    char mqtt_client_id[64];
    char mqtt_topic[64];
}mqtt_ctx_t;
mqtt_ctx_t mqtt_ctx_t_a;

static int mqtt_publish_temphumi(void);
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

float        	temperature, humidity;
int 			rv = -1;
uint8_t		    flag_wifi = 0;
uint8_t			flag_mqtt = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_TIM15_Init();
  MX_USART2_UART_Init();
  Sht30_Init(); 
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  printf("STM32L433CBT6 application program v1.0 start.\r\n");
  rv = esp8266_wifi_init();
  if (rv != 0)
  {
	  printf("ERROR:send at command to config error!(%d)\n", rv);
  }

  process_master();
  get_wlan(mqtt_ctx_t_a.def_router_ssid,mqtt_ctx_t_a.def_router_pwd);
  printf("wifi msg [%s:%s]\n", mqtt_ctx_t_a.def_router_ssid, mqtt_ctx_t_a.def_router_pwd);

  get_mqtt(mqtt_ctx_t_a.mqtt_broker_hostname,&mqtt_ctx_t_a.mqtt_broker_port,mqtt_ctx_t_a.mqtt_client_id,mqtt_ctx_t_a.mqtt_broker_username,mqtt_ctx_t_a.mqtt_broker_password);
  memcpy(mqtt_ctx_t_a.mqtt_topic,"/sys/a1LcxRla2VF/DHT11/thing/event/property/post",strlen("/sys/a1LcxRla2VF/DHT11/thing/event/property/post")+1);

  while (1)
  {
	  	  if (!(flag_wifi & WIFI_CONNECT))
	  	  {

	  		  if ((flag_wifi = esp8266wifi_join_network(mqtt_ctx_t_a.def_router_ssid, mqtt_ctx_t_a.def_router_pwd)) != 0)
	  		  {
	  			  printf("Failed to disconnect and reconnect!(esp8266wifi_join_network)(%d)\n",flag_wifi);
	  			  if (esp8266wifi_ping(AT_PING_ID) != 0)
	  			  {
	  				  printf("send at+ping command failed\n");

	  			  }
	  		  }
	  		  flag_wifi |= WIFI_CONNECT;
	  	  }

	  	  if (!(flag_mqtt & MQTT_CONNECT))
	  	  {
	  		if((flag_mqtt = mqtt_connect(mqtt_ctx_t_a.mqtt_broker_hostname,mqtt_ctx_t_a.mqtt_broker_port, mqtt_ctx_t_a.mqtt_broker_username, mqtt_ctx_t_a.mqtt_broker_password,mqtt_ctx_t_a.mqtt_client_id)) != 0)
	  		{
	  		 //闪蓝灯表示WiFi连接好后又没连接好broker
	  			blink_led(Led0,500);

	  		 printf("MQTT connect [%s:%d] failure, flag_mqtt=%d\r\n", mqtt_ctx_t_a.mqtt_broker_hostname, mqtt_ctx_t_a.mqtt_broker_port, flag_mqtt);
	  		}
	  		else
 	  		{
	  			flag_mqtt |= MQTT_CONNECT;
	  			printf("MQTT connect [%s:%d] ok\r\n", mqtt_ctx_t_a.mqtt_broker_hostname, mqtt_ctx_t_a.mqtt_broker_port);
	  	    }
	  	  }

	  	  if(mqtt_publish_temphumi() != 0)
	  	  {
	  		  //闪绿灯表示没发布成功；
	  		  blink_led(Led2, 500);
	  		  //没发布成功再连接broker
	  		  flag_mqtt &= ~MQTT_CONNECT;

	  		  if (esp8266wifi_ping(AT_PING_ID) != 0)
	  		  {
	  			 //没ping成功再连接network
	  			  flag_wifi &= ~WIFI_CONNECT;
	  			  printf("send at+ping command in mqtt_publish_temphumi() failed\n");

	  		  }
	  	  }
	  	  else
	  	  {
	  	  //亮绿灯表示连接发布成功；
	  		  turn_led(Led1,ON);
	  		  HAL_Delay(10000);
	  	  }

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 18;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_USART2;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
  PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

int mqtt_publish_temphumi(void)
{

	float                              temperature, humidity;
	char                               buf[256];
	int                                rv;

	printf("Start DHT11 sample tempRH and MQTT publish it\n");
/*  
	if( DHT11_SampleData(&temperature, &humidity) < 0 )
	{
		return ;
	}
*/
    Read_IIC_Data(&temperature,&humidity);

	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), "{\"method\":\"thing.service.property.set\",\"id\":\"1387425786\",\"params\":{\"CurrentTemperature_9\":%.2f,\"RelativeHumidity\":%.2f},\"version\":\"1.0.0\"}", temperature, humidity);

	rv = mqtt_publish(buf, Qos0, mqtt_ctx_t_a.mqtt_client_id);

	printf("buf=%s\n", buf);
	printf("MQTT publish topic [%s] with msg '%s' %s, rv=%d\r\n", mqtt_ctx_t_a.mqtt_client_id, buf, rv ? "failure": "ok", rv);

	return 0;

}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
